using System;
using System.Collections.Generic;
using System.Text;

// Isolated Storage
using System.IO.IsolatedStorage;
using System.IO;
using System.Security.Policy;
using System.Xml;
using System.Xml.Serialization;

using WoWAddonRefresh.Entities;

using System.Data.Linq;
using System.Linq;
using System.Linq.Expressions;

namespace WoWAddonRefresh {
    public class IStorage {
        public static Guid VERSION = new Guid("78BE641B-3B3C-4569-AD24-8C49974C02C1");

        #region Credentials Set & Get

        public static Credentials GetCredentials() {
            try {
                return StaticContext.DBContext.Credentials.Where(c => c.SaveCredentials == true).FirstOrDefault();
            }
            catch {
                return null;
            }
        }

        public static void SetCredentials(Credentials credentials) {
            if (credentials.SaveCredentials) {
                ValidateCredentials(credentials);
                Credentials dbCredentials = StaticContext.DBContext.Credentials.Where(c => c.SaveCredentials == true).FirstOrDefault();
                if (dbCredentials == null) {
                    StaticContext.DBContext.Credentials.InsertOnSubmit(credentials);

                }
            }
            StaticContext.DBContext.SubmitChanges();
        }

        public static void ValidateCredentials(Credentials credentials) {
            if (credentials.SaveCredentials) {
                if (credentials.LastDownload == DateTime.MinValue) credentials.LastDownload = DateTime.Now;
            }
        }

        #endregion Credentials Set & Get

        #region SavedAddons Get & Set
        public static List<Addon> GetSavedAddonList(string wowPath) {
            List<Addon> result = new List<Addon>();
            if (wowPath != null) {
                string directoryName = wowPath + @"Interface\Addons\FavoritesAddonsRefresher";
                DirectoryInfo directory = new DirectoryInfo(directoryName);
                if (directory.Exists) {
                    string filename = directoryName + @"\WoWAddons.xml";
                    FileInfo fileInfo = new FileInfo(filename);
                    if (fileInfo.Exists) {
                        StreamReader reader = new StreamReader(fileInfo.FullName);
                        XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Addon>));
                        result = (List<Addon>)xmlSerializer.Deserialize(reader);
                        reader.Close();
                    }
                }
            }
            if (result.Count == 0) {
                try {

                    IsolatedStorageFile isoFile;
                    // Retrieve an IsolatedStorageFile for the current Domain and Assembly.
                    try {
                        isoFile =
                            IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                            IsolatedStorageScope.Assembly |
                            IsolatedStorageScope.Domain,
                            null,
                            null);
                    }
                    catch {
                    }
                    finally {
                        isoFile = IsolatedStorageFile.GetUserStoreForDomain();
                    }

                    IsolatedStorageFileStream isoStream =
                        new IsolatedStorageFileStream("WoWAddons_" + VERSION.ToString().ToUpper() + ".xml",
                        FileMode.Open,
                        FileAccess.Read,
                        isoFile);

                    // We only get this far if a file corresponding to the username exists.
                    // Though you can perform operations on the stream, you cannot get a handle to the file.
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Addon>));
                    TextReader reader = new StreamReader(isoStream);
                    result = (List<Addon>)xmlSerializer.Deserialize(reader);
                    reader.Close();
                    isoFile.Close();
                }
                catch (Exception e) {
                    // Expected exception if a file cannot be not found. This indicates that we have a new user.
                    Console.WriteLine(e.Message);
                }
            }

            return result;
        }

        private static Addon GetByNameLink(List<Addon> addons, string nameLink) {
            foreach (Addon addon in addons) {
                if (addon.NameLink == nameLink) return addon;
            }
            return null;
        }

        public static void SaveAddonList(List<Addon> savedAddons, string wowPath) {

            if (savedAddons.Count == 0) return;

            // delete duplicate
            List<Addon> uniqAddons = new List<Addon>();
            for (int i = (savedAddons.Count - 1); i > -1; i--) {
                Addon savedAddon = savedAddons[i];
                if (savedAddon.NameLink == null || savedAddon.NameLink.Trim().Equals(string.Empty)) savedAddons.RemoveAt(i);
                else if (GetByNameLink(uniqAddons, savedAddon.NameLink) == null) uniqAddons.Add(savedAddon);
            }

            savedAddons = uniqAddons;
            if (wowPath != null) {
                string directoryName = wowPath + @"Interface\Addons\FavoritesAddonsRefresher";
                DirectoryInfo directory = new DirectoryInfo(directoryName);
                if (!directory.Exists) directory.Create();
                string filename = directoryName + @"\WoWAddons.xml";
                StreamWriter writer = new StreamWriter(filename);
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Addon>));
                xmlSerializer.Serialize(writer, savedAddons);
                writer.Close();
            }
            else {
                try {

                    IsolatedStorageFile isoFile;
                    // Retrieve an IsolatedStorageFile for the current Domain and Assembly.
                    try {
                        isoFile =
                            IsolatedStorageFile.GetStore(IsolatedStorageScope.User |
                            IsolatedStorageScope.Assembly |
                            IsolatedStorageScope.Domain,
                            null,
                            null);
                    }
                    catch {
                    }
                    finally {
                        isoFile = IsolatedStorageFile.GetUserStoreForDomain();
                    }

                    IsolatedStorageFileStream isoStream =
                        new IsolatedStorageFileStream("WoWAddons_" + VERSION.ToString().ToUpper() + ".xml",
                        FileMode.Create,
                        FileAccess.Write,
                        isoFile);
                    // We only get this far if a file corresponding to the username exists.
                    // Though you can perform operations on the stream, you cannot get a handle to the file.

                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Addon>));
                    // FileInfo fileInfo = new FileInfo(applicationExecutablePath);
                    TextWriter writer = new StreamWriter(isoStream);
                    xmlSerializer.Serialize(writer, savedAddons);
                    writer.Close();
                    isoFile.Close();
                }
                catch (Exception e) {
                    // Expected exception if a file cannot be not found. This indicates that we have a new user.
                    Console.WriteLine(e.Message);
                }
            }

        }
        #endregion SavedAddons Get & Set
        
    }
}
